#' 散点图拼图
#'
#' @param res U5_mr分析出的res
#' @param dat harmonize后的dat
#' @param point_size 散点的大小
#' @param linewidth 线的宽度
#' @param ggsci_color ggsci包的论文颜色模板
#'
#' @return 散点图
#' @export
#'
#' @examples
#'
#' \dontrun{
#'
#' library(ggplot2)
#'
#' U7_scatter_plot(res,dat)
#'
#' ggsave(paste0("figure2.png"),
#'        width=50, height=21,
#'        units=c("cm"), dpi=900, limitsize=F)
#'
#' # A4纸的标准尺寸为21cm × 29.7cm
#'
#'
#'
#' # 如果图太多，可以挑阳性的作图
#' ivw_sig<-subset(res, res$`pval_Inverse variance weighted`< 0.05)
#' dat_sig<- dplyr::inner_join(dat, ivw_sig[,c('id.outcome','id.exposure')] ,by = dplyr::join_by(id.outcome, id.exposure))
#' U7_scatter_plot(ivw_sig,dat_sig)
#'
#'
#'
#'
#' }
#'
#'
#'
#'
U7_scatter_plot<-function( res, dat,point_size = 2,
                           linewidth=1 ,
                           ggsci_color=ggsci::scale_color_lancet()){

  plot <- scatter_plot(res , dat,point_size = point_size,linewidth=linewidth ,ggsci_color=ggsci_color)

  legend <- plot[[1]]%>%
    ggpubr::get_legend()%>%
    ggpubr::as_ggplot()

  plot_no_legend <- plot %>%
    lapply( function(x){
      x <- x  +
        ggplot2::theme(legend.position = "none")
      return(x)
    }  )

  plot_no_legend[["legend"]]<-legend

  p_all<- do.call(gridExtra::grid.arrange,plot_no_legend )

  return(p_all)
}


scatter_plot<-function( res, dat,point_size = 2,linewidth=1 , ggsci_color=ggsci::scale_color_frontiers()){
  require(TwoSampleMR)
  mr_results <- U6_res_to_TSMR_res(res)
  mrres <- plyr::dlply(dat, c("id.exposure", "id.outcome"),
                       function(d) {
                         d <- plyr::mutate(d)
                         if (nrow(d) < 2 | sum(d$mr_keep) == 0) {
                           return(TwoSampleMR:::blank_plot("Insufficient number of SNPs"))
                         }
                         d <- subset(d, mr_keep)
                         index <- d$beta.exposure < 0
                         d$beta.exposure[index] <- d$beta.exposure[index] *
                           -1
                         d$beta.outcome[index] <- d$beta.outcome[index] *
                           -1
                         mrres <- subset(mr_results, id.exposure == d$id.exposure[1] &
                                           id.outcome == d$id.outcome[1])
                         mrres$a <- 0
                         if ("MR Egger" %in% mrres$method) {
                           temp <- TwoSampleMR::mr_egger_regression(d$beta.exposure,
                                                       d$beta.outcome, d$se.exposure, d$se.outcome,
                                                       default_parameters())
                           mrres$a[mrres$method == "MR Egger"] <- temp$b_i
                         }
                         if ("MR Egger (bootstrap)" %in% mrres$method) {
                           temp <- TwoSampleMR::mr_egger_regression_bootstrap(d$beta.exposure,
                                                                 d$beta.outcome, d$se.exposure, d$se.outcome,
                                                                 default_parameters())
                           mrres$a[mrres$method == "MR Egger (bootstrap)"] <- temp$b_i
                         }
                         ggplot2::ggplot(data = d, ggplot2::aes(x = beta.exposure,
                                                                y = beta.outcome)) + ggplot2::geom_errorbar(ggplot2::aes(ymin = beta.outcome -
                                                                                                                           se.outcome, ymax = beta.outcome + se.outcome),
                                                                                                            colour = "grey", width = 0) + ggplot2::geom_errorbarh(ggplot2::aes(xmin = beta.exposure -
                                                                                                                                                                                 se.exposure, xmax = beta.exposure + se.exposure),
                                                                                                                                                                  colour = "grey", height = 0) + ggplot2::geom_point(size = point_size) +
                           ggplot2::geom_abline(data = mrres, ggplot2::aes(intercept = a,
                                                                           slope = b, colour = method),linewidth = linewidth, show.legend = TRUE) +
                           ggsci_color+
                           ggplot2::labs(colour = "MR Test",x = d$exposure[1], y = d$outcome[1]) + ggplot2::theme(legend.position = "top",
                                                                                                                  legend.direction = "vertical") + ggplot2::guides(colour = ggplot2::guide_legend(ncol = 2))
                       })

  return( mrres)
}
